<template>
  <div class="content">
    <!--头部-->
    <div class="header-setting">
      <a-breadcrumb class="breadcrumb">
        <a-breadcrumb-item>
          <a href="../main">首页</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>值班管理</a-breadcrumb-item>
        <a-breadcrumb-item>轨迹管理</a-breadcrumb-item>
      </a-breadcrumb>
      <!--查询条件-->
      <div class="box-condition-body">
        <div class="box-condition-item">
          <div class="box-item">
            <div style="margin: 0 50px">轨迹上报间隔时间(分钟):</div>
            <template>
              <a-select
                showSearch
                placeholder="时间间隔"
                style="width: 200px"
                optionFilterProp="children"
                :allowClear="true"
                :value="locusTime"
                @change="changeLocusTime"
              >
                <a-select-option v-for="t in timesArr" :key="t.id" :value="t.id"
                  >{{ t.time }}
                </a-select-option>
              </a-select>
            </template>
            <template>
              <div class="button_time">
                <a-button type="primary" @click="saveLocus()">保存</a-button>
              </div>
            </template>
          </div>
        </div>
        <div class="box-condition-item">
          <template>
            <div style="margin: auto 50px">
              巡查日期:
              <a-date-picker @change="onChangeTime" />
            </div>
          </template>
          <template>
            <div style="margin: 0 50px">巡查人员:</div>
            <a-select
              showSearch
              optionFilterProp="children"
              placeholder="巡查员"
              style="width: 200px"
              @change="changeUser"
            >
              <a-select-option v-for="a in users" :key="a.id" :value="a.id"
                >{{ a.name }}
              </a-select-option>
            </a-select>
          </template>
          <template>
            <div class="button_time">
              <a-button type="primary" @click="loadData()">确定</a-button>
            </div>
          </template>
        </div>
      </div>
    </div>

    <!-- <div class="box-form"> -->
    <!--工具栏-->
    <!-- <div class="box-tool">
            <div></div>
            <div style="display: flex">
            </div>
        </div> -->
    <div id="box-map"></div>
    <div id="map-spot" v-show="data.length != 0">
      <a-table
        size="middle"
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        :customRow="customRow"
      >
        <div slot="name" slot-scope="text">{{ formatTime(text) }}</div>
      </a-table>
    </div>
    <!-- </div> -->
  </div>
</template>

<script>
// import AMap from 'vue-amap'
import locus from "../../api/ouduty/Locus";
import Vue from "vue";
const columns = [
  {
    title: "地点",
    dataIndex: "address",
  },
  {
    title: "时间",
    dataIndex: "time",
    scopedSlots: { customRender: "name" },
  },
];
const data = [];
export default {
  name: "locus",
  /*数据层*/
  data() {
    return {
      timesArr: [
        { id: "5", time: "5" },
        { id: "10", time: "10" },
        { id: "20", time: "20" },
        { id: "30", time: "30" },
        { id: "60", time: "60" },
        { id: "90", time: "90" },
        { id: "120", time: "120" },
      ],
      locusTime: "",
      users: [],
      /**按钮**/
      /*在岗时间按钮*/
      selectId: -1,
      /**日期控件**/
      /*收费时间日期*/
      momentArr: [],
      // 地图参数
      pointList: [],
      defaultPoint: [],
      locusArr: [],
      userId: "",
      date: "",
      mapControl: "",
      Polyline: "",
      data,
      columns,
      markerNode: "",
      pagination: {
        showTotal: (total) => `共${total}条`,
        total: 0,
        defaultCurrent: 1,
        showQuickJumper: true,
        current: 1,
        defaultPageSize: 5,
        onChange: (current) => this.changePage(current), //点击当前页码
      },
      landmarkList: "",
    };
  },
  /*方法层*/
  methods: {
    changeLocusTime(bj) {
      this.locusTime = bj;
    },
    getUser() {
      locus.getAllUser().then((res) => {
        if (res.code == 2000) {
          if (res.data != null) {
            this.users = res.data;
          }
        } else {
          this.$message.error("获取用户失败");
        }
      });
    },
    /*添加或修改巡查轨迹上传间隔时间 */
    saveLocus() {
      let obj = {
        time: this.locusTime,
      };
      locus.saveLocus(obj).then((res) => {
        if (res.code == 2000) {
          this.$message.success("保存成功");
        }
      });
    },
    changeUser(userId) {
      this.userId = userId;
    },
    loadData() {
      this.getData();
    },
    async getData() {
      this.locusArr = [];
      this.pointList = [];
      var obj = { userId: this.userId, time: this.date };
      await locus.getLocus(obj).then((res) => {
        if (res.code == 2000) {
          this.locusArr = res.data;
          for (var i in this.locusArr) {
            this.pointList.push(
              new AMap.LngLat(
                this.locusArr[i].longitude,
                this.locusArr[i].latitude
              )
            );
          }
        }
        this.dropMap();
        this.data = this.locusArr;
      });

      let landmark = this.data.map((items, index, arr) => {
        return ++index == arr.length
          ? parseFloat(items.longitude).toFixed(6) +
              "," +
              parseFloat(items.latitude).toFixed(6)
          : parseFloat(items.longitude).toFixed(6) +
              "," +
              parseFloat(items.latitude).toFixed(6) +
              "|";
      });
      landmark = landmark.join(",").replaceAll("|,", "%7c");
      this.landmarkList = landmark;
      await locus
        .getLocusAPI({
          location: landmark,
          batch: true,
          limit: this.pagination.defaultPageSize,
          curr: this.pagination.current,
        })
        .then((res) => {
          if (res.code == 2000) {
            console.log(res.data);
            this.data = res.data.list.map((items, index) => {
              return {
                address: items.address,
                lon: items.lon,
                time: this.data[index].time,
                longitude: this.locusArr[index].longitude,
                latitude: this.locusArr[index].latitude,
              };
            });

            this.pagination.total = res.data.total;
            this.pagination.current = res.data.pageNum;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getLocusTime() {
      locus.getLocusTime().then((res) => {
        if (res.code == 2000) {
          if (res.data != null) {
            this.locusTime = res.data;
          }
        }
      });
    },
    onChangeTime(values) {
      console.log(new Date(values));
      this.date = this.formatDate(new Date(values).getTime());
    },

    /* ------------------------ 画地图 ------------------------ */
    // 实现自定义窗体内容，返回拼接后的字符串
    createInfoWindow(content) {
      // 内容拼接 ...
      return content;
    },
    dropMap() {
      this.mapControl = new AMap.Map("box-map", {
        resizeEnable: true,
        zoom: 18, //地图的层级
      });

      //点标记
      for (var i in this.locusArr) {
        let point = this.locusArr[i];
        // 将创建的点标记添加到已有的地图实例：
        var marker1 = new AMap.Marker({
          position: new AMap.LngLat(point.longitude, point.latitude), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        });
        this.mapControl.add(marker1);

        var marker = new AMap.Marker({
          position: new AMap.LngLat(point.longitude, point.latitude), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          // title: '上报时间:'+point.time,
          offset: new AMap.Pixel(-20, 10),
          content:
            '<div style="background:#aaaaaa;width:50px;opacity:0.6"><font style="font-size: 8px;color:#220088">' +
            this.formatTime(point.time) +
            "</font></div>",
          // icon:"../../images/mark_bs.png",
        });
        this.mapControl.add(marker);
      }
      this.Polyline = new AMap.Polyline({
        // map: mapControl,
        path: this.pointList, // 这里是轨迹的坐标拼成的数组
        showDir: true,
        strokeColor: "#28F", //线颜色
        strokeWeight: 6, //线宽
        borderWeight: 2, // 线条宽度，默认为 1
        lineJoin: "round", // 折线拐点连接处样式
        // strokeStyle: "solid"  //线样式
      });
      this.mapControl.add(this.Polyline); //将这则折线添加到地图
      this.mapControl.setFitView(); //自动调整到合适的位置
    },
    formatDate(value) {
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
    },
    formatTime(value) {
      let date = new Date(value);
      // let y = date.getFullYear();
      // let MM = date.getMonth() + 1;
      // MM = MM < 10 ? "0" + MM : MM;
      // let d = date.getDate();
      // d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      // return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
      return h + ":" + m + ":" + s;
    },
    customRow(record) {
      return {
        on: {
          // 事件
          click: () => {
            if (this.markerNode) {
              this.mapControl.remove(this.markerNode);
            }
            this.markerNode = new AMap.Marker({
              position: new AMap.LngLat(record.longitude, record.latitude), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              icon: new AMap.Icon({
                size: new AMap.Size(40, 50), // 图标尺寸
                image:
                  "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png", // Icon的图像
                imageOffset: new AMap.Pixel(-1, -1), // 图像相对展示区域的偏移量，适于雪碧图等
                imageSize: new AMap.Size(23, 37), // 根据所设置的大小拉伸或压缩图片
              }),
            });
            this.mapControl.add(this.markerNode);

            this.mapControl.setZoomAndCenter(20, [
              record.longitude,
              record.latitude,
            ]); //设置地图中心点
          },
        },
      };
    },
    changePage(current) {
      locus
        .getLocusAPI({
          location: this.landmarkList,
          batch: true,
          limit: this.pagination.defaultPageSize,
          curr: current,
        })
        .then((res) => {
          if (res.code == 2000) {
            this.data = res.data.list.map((items, index) => {
              return {
                address: items.address,
                lon: items.lon,
                time: this.data[index].time,
                longitude: this.locusArr[index].longitude,
                latitude: this.locusArr[index].latitude,
              };
            });

            this.pagination.total = res.data.total;
            this.pagination.current = current;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  /*计算层*/
  computed: {
    computedStyle() {
      return function (selectId) {
        return this.selectId == selectId ? "" : "";
      };
    },
  },
  /*渲染层*/
  mounted() {
    this.getLocusTime();
    this.getUser();
  },
};
</script>

<style scoped>
.content {
  width: 100%;
  height: 100%;
}

.header-setting {
  width: 100%;
  height: 174px;
  background: #fff;
}

.header-setting .breadcrumb {
  margin-left: 41px;
  padding-top: 15px;
}

.box-condition-item {
  display: flex;
  align-items: center;
  min-width: 1500px;
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 5px 0;
}

.box-condition-item .box-item {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 5px 5px 20px 5px;
}

.button_time button {
  margin-left: 10px;
}

#box-map {
  width: 100%;
  height: 80%;
  background: #fff;
}
/* 表单 */
.box-form {
  padding-left: 40px;
  padding-right: 40px;
  min-height: 705px;
  background: #fff;
  margin-top: 8px;
}

.box-form .box-tool {
  padding-top: 11px;
  margin: 8px 0;
  width: 100%;
  /* flex */
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.box-tool button {
  margin-right: 10px;
}

#map-spot {
  width: auto;
  position: absolute;
  right: 0;
  top: 19.5%;
  background: #fff;
  min-width: 20%;
}
</style>
